import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.resps.Tuple;

import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-12-17
 * Time: 10:33
 */
public class RedisZset {

    public static void test1(Jedis jedis) {
        System.out.println("zadd/zrange");

        jedis.flushAll();
        jedis.zadd("key1",99.0,"zhangsan");

        HashMap<String,Double> hashMap = new HashMap<>();
        hashMap.put("lisi",10.0);
        hashMap.put("wangwu",20.0);
        hashMap.put("zhaoliu",30.0);
        jedis.zadd("key1",hashMap);

        List<String> res1 = jedis.zrange("key1", 0, -1);
        System.out.println("res1 = "+res1);

        List<Tuple> res2 = jedis.zrangeWithScores("key1", 0, -1);
        System.out.println("res2 = "+res2);

        String element = res2.get(0).getElement();
        double score = res2.get(0).getScore();
        System.out.println("element = "+element+", score = "+score);
    }

    public static void test2(Jedis jedis) {
        System.out.println("zcard/zrem");

        jedis.flushAll();
        jedis.zadd("key1",11.0,"zhangsan");
        jedis.zadd("key1",22.0,"lisi");
        jedis.zadd("key1",33.0,"wangwu");

        long n = jedis.zrem("key1", "lisi");
        System.out.println("n = "+n);

        List<Tuple> res = jedis.zrangeWithScores("key1", 0 , 1);
        System.out.println("res = "+res);
    }

    public static void test3(Jedis jedis) {
        System.out.println("zscore");

        jedis.flushAll();
        jedis.zadd("key1",11.0,"zhangsan");
        jedis.zadd("key1",22.0,"lisi");
        jedis.zadd("key1",33.0,"wangwu");

        Double zscore = jedis.zscore("key1", "lisi");
        System.out.println("zscore = "+zscore);
    }

    public static void test4(Jedis jedis) {
        System.out.println("zrank/zrevrank");

        jedis.flushAll();
        jedis.zadd("key1",11.0,"zhangsan");
        jedis.zadd("key1",22.0,"lisi");
        jedis.zadd("key1",33.0,"wangwu");

        Long zrank = jedis.zrank("key1", "zhangsan");
        System.out.println("zrank = "+zrank);

        Long zrevrank = jedis.zrevrank("key1", "zhangsan");
        System.out.println("zrevrank = "+zrevrank);

    }

    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:6379");
        try (Jedis jedis = jedisPool.getResource()) {
//            test1(jedis);
//            test2(jedis);
//            test3(jedis);
            test4(jedis);
        }
    }
}
